/*
 * Copyright 2011 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package it.davial.mgwt.client.activities.patient;

import it.davial.mgwt.client.ClientFactory;
import it.davial.mgwt.client.Patient;
import it.davial.mgwt.client.activities.BaseActivity;
import it.davial.mgwt.client.activities.patient.detail.PatientDetailPlace;
import it.davial.mgwt.client.activities.patient.detail.PatientDetailView;
import it.davial.mgwt.client.event.ActionEvent;
import it.davial.mgwt.client.event.ActionNames;
import it.davial.mgwt.client.service.DbServiceAsync;
import it.davial.mgwt.client.ui.widget.PatientCellList;
import it.davial.mgwt.client.ui.widget.cell.PatientCell;

import java.util.List;
import java.util.logging.Logger;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.gwt.user.client.ui.HTML;
import com.googlecode.mgwt.dom.client.event.tap.TapEvent;
import com.googlecode.mgwt.dom.client.event.tap.TapHandler;
import com.googlecode.mgwt.ui.client.dialog.ConfirmDialog;
import com.googlecode.mgwt.ui.client.dialog.ConfirmDialog.ConfirmCallback;
import com.googlecode.mgwt.ui.client.widget.celllist.CellSelectedEvent;
import com.googlecode.mgwt.ui.client.widget.celllist.CellSelectedHandler;

/**
 * Activities are started and stopped by an ActivityManager associated with a container Widget.
 */
public class PatientActivity extends BaseActivity {
	private final static HTML TITLE = new HTML("Patient");
	private PatientCell cell = new PatientCell();
	private static final Logger logger = Logger.getLogger("PatientActivity");
	private List<Patient> patients;
	/**
	 * Used to obtain views, eventBus, placeController.
	 * Alternatively, could be injected via GIN.
	 */
	private ClientFactory clientFactory;

	/**
	 * Sample property.
	 */

	public PatientActivity(ClientFactory clientFactory) {
		super(clientFactory.getPatientView(), "nav");
		this.clientFactory = clientFactory;
	}

	@Override
	public void start(AcceptsOneWidget containerWidget, final EventBus eventBus) {
		logger.info("starting PatientActivity");
		final PatientView view = clientFactory.getPatientView();
		view.getBackbuttonText().setText("Home");

		view.getHeader().setCenterWidget(TITLE);

		view.getMainButtonText().setText("Nav");

	
		addHandlerRegistration(view.getBackbutton().addTapHandler(new TapHandler() {

			@Override
			public void onTap(TapEvent event) {
				ActionEvent.fire(eventBus, ActionNames.BACK);
			}
		}));
		
		addHandlerRegistration(view.getAddButton().addTapHandler(new TapHandler() {

			@Override
			public void onTap(TapEvent event) {
				clientFactory.getPlaceController().goTo(new PatientDetailPlace(null));
			}
		}));
		
		addHandlerRegistration(view.getSearchButton().addTapHandler(new TapHandler() {
			
			@Override
			public void onTap(TapEvent event) {
				findFilteredPatients(view);
			}
		}));

		final PatientCellList list = new PatientCellList(view, clientFactory,cell);
		
		list.setCellDeleteHandler(new CellSelectedHandler() {
			
			@Override
			public void onCellSelected(final CellSelectedEvent event) {
				ConfirmDialog dialog = new ConfirmDialog("Delete","Areu u sure ?", new ConfirmCallback() {
					
					@Override
					public void onOk() {
						Patient patient = list.getModel(event.getIndex());
						removePatient(view, patient);
					}
					
					@Override
					public void onCancel() {
						
					}
				});
				dialog.show();

			}
		});
		
		
		view.setPatientCellList(list);
	
		addHandlerRegistration(view.getEditButton().addTapHandler(new TapHandler() {

			@Override
			public void onTap(TapEvent event) {
			
				boolean edit = cell.isEdit();
				logger.info("edit=" + edit);
				cell.setEdit(!edit);
				view.setPatients(patients);
			}
		}));

		fillPatientList(view);
		containerWidget.setWidget(view.asWidget());
	}

	@Override
	public String mayStop() {
		cell.setEdit(false);
		return null;
	}

	/**
	 * @see PatientDetailView.Presenter#goTo(Place)
	 */
	public void goTo(Place place) {
		clientFactory.getPlaceController().goTo(place);
	}
	
	private void fillPatientList(final PatientView view){
		view.getHeader().setCenterWidget(progressHeader);
		DbServiceAsync.Util.getInstance().getAllPatient(new AsyncCallback<List<Patient>>() {
			
			@Override
			public void onSuccess(List<Patient> result) {
				logger.info("success, result=" + result);
				patients = result;
				view.setPatients(patients);
				view.getHeader().setCenterWidget(TITLE);
			}
			
			@Override
			public void onFailure(Throwable caught) {
				logger.info("Error" + caught );
				view.getHeader().setCenterWidget(TITLE);
				
			}
		});
	
	}

	private void findFilteredPatients(final PatientView view){
		view.getHeader().setCenterWidget(progressHeader);
		DbServiceAsync.Util.getInstance().getFilteredPatient(view.getSurname(), null, new AsyncCallback<List<Patient>>() {
			
			@Override
			public void onSuccess(List<Patient> result) {
				logger.info("success, result=" + result);
				patients = result;
				view.setPatients(patients);
				view.getHeader().setCenterWidget(TITLE);
				
			}
			
			@Override
			public void onFailure(Throwable caught) {
				logger.info("Error" + caught );
				view.getHeader().setCenterWidget(TITLE);
				
			}
		});	
	}

	private void removePatient( final PatientView view,Patient patient ){
		view.getHeader().setCenterWidget(progressHeader);
		DbServiceAsync.Util.getInstance().deletePatient(patient, new AsyncCallback<Boolean>() {
			
			@Override
			public void onSuccess(Boolean result) {
				logger.info("delete patient success = " + result);
				fillPatientList(view);
			}
			
			@Override
			public void onFailure(Throwable caught) {
				logger.info("delete patient failure," + caught);
				
			}
		});
	}

	
	
}
